package spinning

import (
	"encoding/json"
	"fmt"
	"math/big"
	"net/http"

	mqtt "github.com/eclipse/paho.mqtt.golang"
	_ "github.com/mattn/go-sqlite3"
)

func (app *SpinningApp) handleMqttSpindleVoltageMsg(client mqtt.Client, message mqtt.Message) {
	// 处理 从 MCU 发送来的消息

	fmt.Println("### edgex/event/mcu/voltages begin ###")
	//fmt.Printf("======== \n message.Payload(): \n %s \n =======", message.Payload())

	// 机台状态 转换成 纺纱周期、停车记录
	// 将MCU发送来的数据 保存到 全局变量中：realtimeInfo
	payload := message.Payload()
	var payload_length = uint16(len(payload))
	var header_len = uint16(3*2 + 8)
	// 检查 帧头
	identity := uint16(payload[1])<<8 + uint16(payload[0])
	if identity != 0xF5F5 {
		fmt.Printf("### handleMqttSpindleVoltageMsg FrameIdentity: %d unmatch !!! ###\n", identity)
		return
	}

	DataLen := uint16(payload[3])<<8 + uint16(payload[2])

	var loop_length = payload_length
	//dest_len := uint16(len(app.currentVoltagesRes.Voltages)) + header_len
	//dest_len := uint16(unsafe.Sizeof(app.currentVoltagesRes))
	dest_len := uint16(2*3 + 8 + 3000*2)
	if loop_length > dest_len {
		loop_length = dest_len
	}

	// ### DataLen 6010 , payload_length 6014 , header_len 14， loop_length 6014, dest_len 6014 ###
	fmt.Printf("### DataLen %d , payload_length %d , header_len %d， loop_length %d, dest_len %d ###\n",
		DataLen, payload_length, header_len, loop_length, dest_len)
	if DataLen+4 != payload_length || payload_length <= header_len {
		return
	}

	Spindle := uint16(payload[5])<<8 + uint16(payload[4])
	Tid := uint64(payload[13])<<56 + uint64(payload[12])<<48 +
		uint64(payload[11])<<40 + uint64(payload[10])<<32 +
		uint64(payload[9])<<24 + uint64(payload[8])<<16 +
		uint64(payload[7])<<8 + uint64(payload[6])

	app.currentVoltagesRes.DataLen = DataLen
	app.currentVoltagesRes.Spindle = Spindle
	app.currentVoltagesRes.Tid = Tid

	//fmt.Printf("### payload { ###\n %v \n ### } payload ###", payload)

	//if mcuVoltages.Tid == uint64(app.currentVoltagesCmd.Tid) {
	// 复制 电压波形点数组 数据
	//copy(app.currentVoltagesRes.Voltages[0:], mcuVoltages.Voltages[0:])

	for payload_idx := header_len; payload_idx < loop_length; payload_idx += 2 {

		res_idx := (payload_idx - header_len) / 2
		fmt.Printf("## payload_idx: %d , res_idx: %d ###\n", payload_idx, res_idx)

		val := uint16(payload[payload_idx+1])<<8 + uint16(payload[payload_idx])
		var a = big.NewFloat(float64(val))
		var b = big.NewFloat(4096)
		_c, _ := new(big.Float).Quo(a, b).Float64()
		var c = big.NewFloat(_c)
		var d = big.NewFloat(3300)
		e, _ := new(big.Float).Mul(c, d).Float32()
		//tmp := uint16(((mcuVoltages.Voltages[i]) / (4096 * 0.001)) * 3300)
		dest := uint16(e)
		app.currentVoltagesRes.Voltages[res_idx] = val
		app.currentVoltagesRes.Voltages[res_idx] = dest
		//fmt.Printf("# Voltages[i]: %d, e:%v, dest: %d  #\n", mcuVoltages.Voltages[i], e, dest)
	}

	// 修改 命令状态状态
	app.currentVoltagesCmd.Status = 1
	// }

	fmt.Printf("\n%v\n", app.currentVoltagesRes)
	fmt.Println("### edgex/event/mcu/voltages end ###")
}

func (app *SpinningApp) handleMqttSpindleVoltageMsg_bk(client mqtt.Client, message mqtt.Message) {
	// 处理 从 MCU 发送来的消息

	fmt.Println("### edgex/event/mcu/voltages begin ###")
	//fmt.Printf("======== \n message.Payload(): \n %s \n =======", message.Payload())

	// 机台状态 转换成 纺纱周期、停车记录
	// 将MCU发送来的数据 保存到 全局变量中：realtimeInfo
	var mcuVoltages = McuVoltages_Response{} // 临时接收 机台 实时产量 数据
	err := json.Unmarshal(message.Payload(), &mcuVoltages)
	if err != nil {
		fmt.Printf("Error unmarshaling payload: %s\n", err)
		return
	}
	fmt.Printf("### mcuVoltages { ###\n %v \n ### } mcuVoltages ###", mcuVoltages.Voltages)

	//if mcuVoltages.Tid == uint64(app.currentVoltagesCmd.Tid) {
	// 复制 电压波形点数组 数据
	//copy(app.currentVoltagesRes.Voltages[0:], mcuVoltages.Voltages[0:])
	for i := 0; i < len(mcuVoltages.Voltages); i++ {
		var a = big.NewFloat(float64(mcuVoltages.Voltages[i]))
		var b = big.NewFloat(4096)
		_c, _ := new(big.Float).Quo(a, b).Float64()
		var c = big.NewFloat(_c)
		var d = big.NewFloat(3300)
		e, _ := new(big.Float).Mul(c, d).Float32()
		//tmp := uint16(((mcuVoltages.Voltages[i]) / (4096 * 0.001)) * 3300)
		dest := uint16(e)
		app.currentVoltagesRes.Voltages[i] = dest
		//fmt.Printf("# Voltages[i]: %d, e:%v, dest: %d  #\n", mcuVoltages.Voltages[i], e, dest)
	}
	// 修改 命令状态状态
	app.currentVoltagesCmd.Status = 1
	app.currentVoltagesRes.Tid = mcuVoltages.Tid
	app.currentVoltagesRes.Spindle = mcuVoltages.Spindle
	//app.currentVoltagesRes.Ts = mcuVoltages.Ts

	//}
	fmt.Printf("\n%v\n", app.currentVoltagesRes)
	fmt.Println("### edgex/event/mcu/voltages end ###")
}

func (app *SpinningApp) getSpindleVoltags(w http.ResponseWriter, req *http.Request) {

	fmt.Println("### http.getSpindleVoltags() begin ###")
	// 1 获取到 用户请求的锭号
	err := req.ParseForm()
	if err != nil {
		respondError(app.lc, w, http.StatusInternalServerError,
			fmt.Sprintf("Failed to get spinnings list: %v", err))
		return
	}

	// 返回 电压值数组
	if app.currentVoltagesCmd.Status == 1 {
		respondJson(app.lc, w, app.currentVoltagesRes)
	}

	fmt.Println("### http.getSpindleVoltags() end ###")
}
